package cn.apotato.security.interceptor;

import cn.apotato.common.core.constant.SecurityConstants;
import cn.apotato.common.core.context.SecurityContextHolder;
import cn.apotato.common.core.utils.ServletUtils;
import cn.apotato.common.core.utils.StringUtils;
import cn.apotato.common.model.LoginUser;
import cn.apotato.security.auth.AuthUtil;
import cn.apotato.security.utils.SecurityUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.apotato.common.core.constant.SecurityConstants.LOGIN_USER;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author 胡晓鹏
 * @date 2023/05/30
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    /**
     * 执行处理程序之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setOrgId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_ORG_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));

        String token = SecurityUtils.getToken();
        // 通过token获取用户信息
        if (StringUtils.isNotEmpty(token)) {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (loginUser != null) {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(LOGIN_USER, loginUser);
            }
        }
        return true;
    }


    /**
     * 完成后
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }
}
